package task4;

import java.io.*;
import java.net.Socket;

/**
 * 客户端
 */
public class Client{
    public static void main(String[] args) {
        // 定义Socket类型对象
        Socket socket = null;
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            // 提供服务器的IP地址和端口号
            socket = new Socket("127.0.0.1",9000);
            // 创建一个UserMessage对象
            UserMessage userMessage = new UserMessage("check",new User("admin","123456"));
            // 想服务器输出数据
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(userMessage);
            // 接受服务器的数据
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            userMessage = (UserMessage)objectInputStream.readObject();
            System.out.println("正在登陆，请稍等。。。");
            Thread.sleep(5000);
            // 客户机是否登陆成功
            if (userMessage.getType().equals("success"))
                System.out.println("用户登陆成功！");
            else if (userMessage.getType().equals("failed"))
                System.out.println("用户登陆失败！");
            else
                System.out.println("没传过来");

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
